package com.example.bes013.web.demo.config;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Configuration
public class ConditionalSessionFilterConfig {

    @Bean
    public FilterRegistrationBean<ConditionalSessionByUriFilter> sessionByUriFilter() {
        FilterRegistrationBean<ConditionalSessionByUriFilter> registrationBean = new FilterRegistrationBean<>();

        registrationBean.setFilter(new ConditionalSessionByUriFilter());
        registrationBean.setOrder(0); // 确保比 Spring Session Filter 更早执行
        registrationBean.addUrlPatterns("/*");

        return registrationBean;
    }

    public static class ConditionalSessionByUriFilter extends OncePerRequestFilter {

        @Override
        protected void doFilterInternal(HttpServletRequest request,
                                        HttpServletResponse response,
                                        FilterChain filterChain)
                throws ServletException, IOException {

            String uri = request.getRequestURI();

            if (uri.startsWith("/no-session") || uri.startsWith("/static") || uri.startsWith("/health")) {
                // 包装 request，使其无法创建或获取 session
                HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
                    @Override
                    public HttpSession getSession(boolean create) {
                        return null;
                    }

                    @Override
                    public HttpSession getSession() {
                        return null;
                    }
                };
                filterChain.doFilter(wrapper, response);
            } else {
                // 正常走 Spring Session 流程
                filterChain.doFilter(request, response);
            }
        }
    }
}
